package com.gugee.tiktok.web.controller;

import com.gugee.common.web.system.promise.Limit;
import com.gugee.common.web.system.promise.RequestLimit;
import com.gugee.common.web.system.user.dto.UserReceiveDto;
import com.gugee.common.web.system.user.model.User;
import com.gugee.common.web.system.user.service.UserService;
import com.gugee.tiktok.web.service.VerityCodeService;
import com.gugee.common.web.util.Ret;
import com.gugee.common.web.util.jwt.JwtUtil;
import com.gugee.common.web.config.exception.ParamsException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@RestController
@Api(value = "用户管理",tags = {"用户管理"})
public class UserController extends TikTokBaseController {

    @Autowired
    UserService userService;
    @Autowired
    User.UserReceiveMapper userMapper;

    @Autowired
    private VerityCodeService verityCodeService;
    @Autowired
    JwtUtil jwtUtil;
    @Value("${jwt.head}")
    String authorized;

    @Autowired
    ValidateController validateController;

    String activeHtml = "<div style=\"width:100%;max-width: 440px;\"><div style=\"max-width:100%;background-color: #f1f1f1; padding: 20px 16px; font-weight: bold;font-size: 20px;color: rgb(22,24, 35)\">Hi {FirstName},</div>\n" +
            "         <div style=\"max-width: 100%; background-color: rgb(248, 248, 248); padding: 24px 16px;\">\n" +
            "            <p style=\"font-size: 17px; margin-bottom: 20px;\">To activate your sub-account, please click the bottom below. The link will expire in 24 hours. </p>\n" +
            "            <a href=\"https://webapi.gugeedata.com/v1/verify/subuser?data={data}\" style=\"font-size: 17px;\" rel=\"noopener\" target=\"_blank\">\n" +
            "                <div style=\"font-size: 15px; color: rgb(255, 255, 255); font-weight: bold; background-color: rgb(254, 44, 85); border-radius: 2px; text-align: center; height: 44px; line-height: 44px;\">Activate your subaccount</div><span style=\"font-size: 17px;\"><font></font></span>\n" +
            "            </a>\n" +
            "            <span style=\"font-size: 17px;\"><font></font></span>\n" +
            "            <span style=\"font-size: 17px;\"><font></font></span>\n" +
            "            <span style=\"font-size: 17px;\"><font></font></span>\n" +
            "            <div class=\"unbind_email\" style=\"\">\n" +
            "              <p style=\"\"><span style=\"font-size: 17px;\">If you did not request this activation email, you can ignore this message.</span><br><br><span style=\"font-size: 17px;\">Gugee Data Support Team</span></p></div></div></div>";


    @ApiOperation(value = "添加子用户",notes = "添加子用户")
    @RequestMapping(value = "user/child",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @RequestLimit(value = "AddSubAccount",validateType = Limit.ADD_SUB_USER)
    public String addUser(@Valid @RequestBody UserReceiveDto userDto) throws UnsupportedEncodingException {
        if(null != userService.getUserByEamil(userDto.getEmail())){
            //return Ret.err("该邮箱已注册！");
            return Ret.err("This email has been registered");
        }

        userDto.setParentId(getUser().getId());
        User u = userMapper.mapper(userDto);
        u.setActivation(false);
        u.setCreateBy("UserController->addUser");
        u.setUpdateBy("UserController->addUser");
        String data = URLEncoder.encode("{\"email\":\"{email}\"}".replace("{email}",u.getEmail()),"UTF-8");
        userService.saveUser(u);
        validateController.sendHtmlMail(u.getEmail(),"Activate your subaccount with Gugee Data",activeHtml.replace("{FirstName}",u.getFirstName()).replace("{data}",data));
        return Ret.success("subAccount success!");
    }

    @ApiOperation(value = "获取子帐号列表",notes = "获取子帐号列表")
    @RequestMapping(value = "user/child",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String getUserList(){
        val userList = userService.getUserList(super.getUser().getId());
        return Ret.pageData(userList.size(),userList);
    }


    @ApiOperation(value = "删除子帐号",notes = "删除子帐号")
    @RequestMapping(value = "user",method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
    public String deleteAweme(@RequestBody String body) throws ParamsException {
        val userId = getParam(Long.class,body,"userId");
        val user = userService.getUser(userId);

        if(null == user){
           return Ret.err("Not exist subaccount");
        }

        if(getUser().getId() != user.getParentId()){
            return Ret.err("Not you subaccount");
        }

        userService.deleteAccount(userId);
        return Ret.success("Success delete subaccount");
    }

    @ApiOperation(value = "获取用户信息",notes = "获取用户信息")
    @RequestMapping(value = "user/info",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String getUserInfo(){
        return Ret.success("获取成功!",userService.getUser(super.getUser().getId()));
    }

    @ApiOperation(value = "密码重置",notes = "密码重置", produces = "application/json;charset=UTF-8")
    @RequestMapping(value = "user/rest/pwd", method=RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    public String resetPassword(@RequestBody String body) throws ParamsException {
        String email = getParam(body,"email");
        String code = getParam(body,"code");;
        String newPassword = getParam(body,"newPassword");;
        User user = userService.getUserByEamil(email);

        if(null == user){
            return Ret.err("Not find user");
        }

        if(!verityCodeService.validate(email,code)){
            return Ret.err("Verification code is invalid");
        }
        user.setPassword(newPassword);
        user.setUpdateBy("UserController->resetPassword");
        userService.saveUser(user);
        String token = userService.login(user);
        setCookie(authorized,token);
        return Ret.success("Rest password success");
    }

    @ApiOperation(value = "修改密码",notes = "修改密码", produces = "application/json;charset=UTF-8")
    @RequestMapping(value = "user/change/pwd", method=RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    public String changePassword(@RequestBody String body) throws ParamsException {
        String newPwd = getParam(body,"newPwd");
        User user =getUser();

        if(!StringUtils.isEmpty(user.getPassword())){
            String curPwd = getParam(body,"curPwd");
            if(!user.getPassword().equals(curPwd)){
                return Ret.err("Current password is invalid");
            }
        }
        user.setPassword(newPwd);
        userService.saveUser(user);
        String token = userService.login(user);
        setCookie(authorized,token);
        return Ret.success("Change password success！");
    }
}
